package server.mapper;

import server.HttpServlet;
import server.WebappClassLoader;

import java.io.File;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xingyi
 */
public class Context {
    private WebappClassLoader webappClassLoader;
    private String contextPath;
    private Map<String, Wrapper> wrapperMap = new HashMap<>();

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public void addWrapper(File docBase, Wrapper wrapper) throws MalformedURLException {
        if (webappClassLoader == null) {
            webappClassLoader = new WebappClassLoader(docBase);
        }
        wrapper.setClassLoader(webappClassLoader);
        wrapperMap.put(wrapper.getUrlPattern(), wrapper);
    }

    public HttpServlet getServlet(String url) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        final Wrapper wrapper = wrapperMap.get(url);
        if (wrapper == null) {
            return null;
        }
        return wrapper.newServletInstance();
    }

}
